//
//  YJLogonViewController.swift
//  yuejian
//
//  Created by yanziye on 2017/9/29.
//  Copyright © 2017年 gyy. All rights reserved.
//

import UIKit
class YJLogonViewController: UIViewController {

    
    
    @IBOutlet weak var userName: UITextField!
    
    
    @IBOutlet weak var passWord: UITextField!
    
    
    @IBAction func logon(_ sender: UIButton) {
        
        
        //取得用户名和密码，使用keychain保存用户名和密码
        if userName.text == "" {
            //显示提示，调用MBProgressHUD的扩展功能
            //print("用户名没有输入")
            MBProgressHUD.showDelayHUDToView(self.view, message: "用户名没有输入")
            
        } else {
            if passWord.text == "" {
                MBProgressHUD.showDelayHUDToView(self.view, message: "密码没有输入")
            } else {
                let parameters: NSDictionary = ["username": userName.text!,"userpass": passWord.text!] as NSDictionary
                YJNetworkMngTool.sharedNetWorkMngTool().YJNetwork_Logon(parameters, view: self.view, block: { (flag) -> Void in
                    if flag == "1" {
                        //本地存储用户的其他信息
                        YJLogonReturnModel.getUserInformation()
                        
                        let _ = (ACSimpleKeychain.defaultKeychain() as AnyObject).storeUsername(self.userName.text, password: self.passWord.text, identifier: "user1", forService: "userpassword")
                        //登陆到主界面
                        //测试暂时先把这句去掉
                 //       UIApplication.shared.keyWindow!.rootViewController = YJMainTabBarController()
                    } else {
                        //清空用户名和密码
                        let _ = (ACSimpleKeychain.defaultKeychain() as AnyObject).deleteAllCredentials(forService: "userpassword")
                        let _ =  (ACSimpleKeychain.defaultKeychain() as AnyObject).storeUsername("", password: "", identifier: "user1", forService: "userpassword")
                    }
                })
                
            }
        }
    }
    
    //用户密码保存与否的选择，按钮的几种状态：default 按钮的默认状态，highlighted 当用户点击了按钮，没有抬起的那段时间；selected这种状态和用户的操作无关，用户操作不会将按钮改成selected状态，只能用代码改变。
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //从keychain中取出用户名和密码，如果取到则自动填充到控件中
       //featchUserNamePwd()
    }
    //封装函数取用户名和密码
    func featchUserNamePwd() {
        
        let userPwdDict = (ACSimpleKeychain.defaultKeychain() as AnyObject).credentials(forIdentifier: "user1", service: "userpassword") as NSDictionary
        if userPwdDict.count != 0  {
            userName.text = userPwdDict.object(forKey: "username") as? String
            passWord.text = userPwdDict["password"] as? String
        }
    }
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.userName.resignFirstResponder()
        self.passWord.resignFirstResponder()
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    
}
